#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "termInput.h"

int addChar(termInput term, char c) {
	int j;

	if(++(term->size) == term->buffer_size) {
		term->buffer_size += term->buffer_increase_rate;
		term->buffer = (char *)realloc(term->buffer,term->buffer_size*sizeof(char));
	}
	for(j=term->size-1;j >= term->cursor_pos;j--) {
		term->buffer[j+1] = term->buffer[j];
	}
	term->buffer[++j] = c;
	(term->cursor_pos)++;

	return 1;
}

int removeChar(termInput term) {
	int j;

	if(term->cursor_pos == 0 || term->cursor_pos > term->size) {
		return 0;
	}

	for(j=term->cursor_pos-1;j < term->size;j++) {
		term->buffer[j] = term->buffer[j+1];		
	}

	(term->size)--;
	(term->cursor_pos)--;

	return 1;		

}

termInput createTermInput(int buffer_size, int buffer_increase_rate) {
	termInput t = (termInput)malloc(sizeof(struct _TERMINAL_INPUT));
	
	if(t == NULL)
		return NULL;
	
	t->buffer_size = buffer_size;
	t->buffer_increase_rate = buffer_increase_rate;
	t->buffer = (char *)malloc(buffer_size*sizeof(char));

	if(t->buffer == NULL)
		return NULL;

	t->buffer[0] = '\0';
	t->size = 0;
	t->cursor_pos = 0;

	return t;
}

int replaceBuffer(termInput t, char *s) {
	int size = strlen(s);

	if(size + 1 > t->buffer_size) {
		t->buffer = (char *)malloc((t->buffer_size + t->buffer_increase_rate)*sizeof(char));

		if(t->buffer == NULL) {
			return 0;
		}
	}

	strcpy(t->buffer,s);
	t->size = strlen(t->buffer);
	t->cursor_pos = t->size;

	return 1;
}

int moveCursor(termInput t, int dir) {
	if(dir == LEFT) {
		if(t->cursor_pos > 0) {
			(t->cursor_pos)--;
			return 1;
		} else {
			return 0;
		}
	} else if(dir == RIGHT) {
		if(t->cursor_pos < t->size) {
			(t->cursor_pos)++;
			return 1;
		} else {
			return 0;
		}
	} else {
		return 0;
	}
}
void posCursor(termInput term) {
	int offset = term->size - term->cursor_pos;
	int i;

	for(i=0;i<offset;i++)
		printf("%c[1D",27);
	
}
